package com.basic.common.utils.easyExcel;

import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ImageData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import cn.idev.excel.util.IoUtils;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * excel导出图片地址转换器
 *
 * @author zhaoxy_jn@163.com
 */
@Slf4j
public class ExcelImgUrlConverter implements Converter<String> {

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        List<ImageData> imageDataList = new ArrayList<>();
        WriteCellData<Void> writeCellData = new WriteCellData<>();
        try {
            // 如果 value 为 null 或空字符串，直接返回空单元格
            if (value == null || value.trim().isEmpty()) {
                writeCellData.setType(CellDataTypeEnum.STRING);
                return writeCellData;
            }
            URL imageUrl = new URL(value);
            byte[] bytes = IoUtils.toByteArray(imageUrl.openConnection().getInputStream());
            ImageData imageData = new ImageData();
            imageData.setImage(bytes);
            imageDataList.add(imageData);
        } catch (Exception ignored) {
            log.error("解析URL失败");
        }

        writeCellData.setImageDataList(imageDataList);
        writeCellData.setType(CellDataTypeEnum.STRING);
        return writeCellData;
    }
}
